package org.example.service.middlegateway.service;

import com.alibaba.fastjson.JSONObject;
import org.example.service.middlegateway.domain.dto.SearchParamsDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
public class EsService {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${elasticsearch.uri}")
    private String esUri;
    @Value("${elasticsearch.username}")
    private String esUsername;
    @Value("${elasticsearch.password}")
    private String esPassword;

    public JSONObject search(SearchParamsDTO searchParams) {
        String url = esUri+"/"+searchParams.getIndex()+"/_search";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 添加用户名和密码
        Base64.Encoder encoder = Base64.getEncoder();
        String authorization = esUsername+":"+esPassword;
        String encodeAuthorization = encoder.encodeToString(authorization.getBytes(StandardCharsets.UTF_8));
        headers.add("Authorization", "Basic " + encodeAuthorization);
        // 时间过滤
        JSONObject jsonObjectStatement = JSONObject.parseObject(searchParams.getStatement());
        String postFilterStr = "{\"range\": {\"create_time\": {\"gte\": \""+searchParams.getStartTime()+"\",\"lte\": \""+searchParams.getEndTime()+"\",\"format\": \"yyyy-MM-dd HH:mm:ss\"}}}";
        JSONObject jsonObjectPostFilter = JSONObject.parseObject(postFilterStr);
        jsonObjectStatement.put("post_filter", jsonObjectPostFilter);
        String statementStr = JSONObject.toJSONString(jsonObjectStatement);

        HttpEntity<String> entity = new HttpEntity<>(statementStr, headers);
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class);

        return exchange.getBody();
    }
}
